package com.tbeasy.financial;

import android.app.TabActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TabHost;

import com.tbeasy.financial.provider.DatabaseHelper;
import com.tbeasy.financial.provider.DatabaseUtil.TableCategory;

/**
 * 
 * 
 * @author Andy
 * 
 */
public class MainActivity extends TabActivity {
	
	private static final String TAB_YEARTRANS = "tab_yeartrans";
	private static final String TAB_REPORT = "tab_report";
	private static final String TAB_ACCOUNT = "tab_account";
	
	private LinearLayout tabYeartrans;
	private LinearLayout tabReport;
	private LinearLayout tabAccount;
	
	private TabHost mTabHost;
	
	private DatabaseHelper helper;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		
		mTabHost = this.getTabHost();
		mTabHost.addTab(mTabHost.newTabSpec(TAB_ACCOUNT).setIndicator(TAB_ACCOUNT)
				.setContent(new Intent(this, AccountActivity.class)));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_YEARTRANS).setIndicator(TAB_YEARTRANS)
				.setContent(new Intent(this, TransactionActivity.class)));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_REPORT).setIndicator(TAB_REPORT)
				.setContent(new Intent(this, AddTransactionActivity.class)));
		
		tabYeartrans = (LinearLayout) findViewById(R.id.tab_yeartrans);
		tabReport  = (LinearLayout) findViewById(R.id.tab_report);
		tabAccount = (LinearLayout) findViewById(R.id.tab_account);
		
		tabYeartrans.setOnClickListener(tabClickListener);
		tabReport.setOnClickListener(tabClickListener);
		tabAccount.setOnClickListener(tabClickListener);
		
		helper = new DatabaseHelper(this);
		if(checkCategoryDataExsits()) {
			helper.addCategoryData();
		}
		
		
	}
	
	private OnClickListener tabClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tab_yeartrans:
				mTabHost.setCurrentTabByTag(TAB_YEARTRANS);
				break;
				
			case R.id.tab_report:
				mTabHost.setCurrentTabByTag(TAB_REPORT);
				break;
			
			case R.id.tab_account:
				mTabHost.setCurrentTabByTag(TAB_ACCOUNT);
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		if(null != helper ) {
			
			helper.close();
		}
		super.onDestroy();
	}
	
	private boolean checkCategoryDataExsits() {
		Cursor cursor = helper.getReadableDatabase().query(TableCategory.TAB_NAME, null, null, null, null, null, null);
		if(cursor != null && cursor.moveToFirst()) {
			return false;
		}
		return true;
	}
	
}